# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import logging,sys
from piHAlibs import (my_fctname,coroutine)
from .parsers import TSDUOParsers

logger = logging.getLogger()

def valueofmsg(item,pair):
    msg = item.split(';')
    for pv in msg:
         if pair in pv:
              return pv.split(':')[1]
    return None
        

def item2msgs(item):
    if not item[1].startswith('protocol') : return None
    namedev = item[0]
    if 'TSDUO' not in namedev : return None
    protocol = valueofmsg(item[1],'protocol')
    if not protocol : return None
    sdata = valueofmsg(item[1],'data')
    if not sdata : return None
    if sdata[:2] == '0x' : sdata = sdata[2:]
    if protocol in ('oregon','arctech'):
       	model = valueofmsg(item[1],'model').lower()
    else:
        model = 'NC'
    if protocol == 'oregon':
        sdata = model[2:] + sdata
    logger.debug("Data to decode %s",repr(sdata))
    if sys.hexversion > 0x030000F0:
        p = [ y for y in bytes.fromhex(sdata) ]
    else:
        p = [ ord(y) for y in sdata.decode('hex') ]
    data = ['0x%02x' % i for i in p]
    logger.debug("Packet to decode %s",repr(data))
    return [namedev, protocol, data, p, model]


@my_fctname
@coroutine
def TSDUOparser(decoders,rejected=None):
    """
    item = [namedev,events]
    split events (if several) before sending to TSDUOparser1
    """
    while True:
        events = (yield)
        logger.debug("Event receive %s",repr(events))
        #['TSD0:TSDUO','protocol:arctech;model:selflearning;data:0x1FF3BAB0|protocol:arctech;model:selflearning;data:0x1FF3BAB0']
        evts = events[1].split('|')
        if len(evts) > 1:
            for event in evts:
                TSDUOparser1(decoders,rejected=None).send([events[0],event])
        else:
            TSDUOparser1(decoders,rejected=None).send(events)
 

@my_fctname
@coroutine
def TSDUOparser1(decoders,rejected=None):
    """
    Parse protocol model for TellStick Duo Controller
    item = [namedev,[events]]
    Send to next target = decoder
    """
    hdps = TSDUOParsers
    while True:
        item = (yield)
        logger.debug("Event receive %s",repr(item))
        #['TSD0:TSDUO','protocol:arctech;model:selflearning;data:0x1FF3BAB0']
        msgs = item2msgs(item)
        if not msgs : continue
        logger.debug("%s",repr(msgs))
        hdp = (msgs[1],msgs[4])
        if hdp not in hdps:
            if rejected: rejected.send(['NEW_PROTSD',hdp] + item)
            continue
        msgs.append(hdps[hdp][1])	#Header 
        msgs.append(item[1])	#raw evt 
        logger.debug("%s",repr(msgs))
        for target in decoders:
            logger.debug("Data sent to %s",repr(target))
            target.send(msgs)

